當涉及到字串和字元處理時,Python 提供了許多內建的方法和函式來處理這些操作。以下是一個簡單的教學,其中包含一些常見的字串和字元處理操作,並附上相關的範例程式碼。

一、 字串建立
在 Python 中,你可以使用單引號或雙引號來建立字串。

str1 = 'Hello, world!'
str2 = "Python Programming"

二、 字串連接
你可以使用加號運算子 (+) 來連接兩個字串。

str1 = 'Hello, world!'
str2 = "Python Programming"
str3 = str1 + ' ' + str2
print(str3)  # 輸出: Hello, world! Python Programming

三、 字串長度
你可以使用 len() 函式獲取字串的長度。

str1 = 'Hello, world!'
length = len(str1)
print(length)  # 輸出: 13

四、 子字串提取
你可以使用索引 (index) 來提取字串中的特定部分。索引從 0 開始,最後一個字元的索引是字串長度減一。

# 注意 Python list index 是從 0 開始
sub_string = str1[7:12]
print(sub_string)  # 輸出: world

五、 字符串分割
你可以使用 split() 方法將字串分割成子字串,分割依據是指定的分隔符號。

words = str2.split(' ')
print(words)  # 輸出: ['Python', 'Programming']

六、 字串替換
你可以使用 replace() 方法來替換字串中的特定子字串。

new_str = str1.replace('world', 'Python')
print(new_str)  # 輸出: Hello, Python!

七、 字元提取
你可以使用索引 (index) 提取字串中的單個字元。注意 Python list index 是從 0 開始! 

char = str1[4]
print(char)  # 輸出: o

八、 字元轉換
你可以使用 ord() 函式將字元轉換為對應的 Unicode 數字,或使用 chr() 函式將 Unicode 數字轉換為對應的字元。

unicode_value = ord('A')
print(unicode_value)  # 輸出: 65

character = chr(97)
print(character)  # 輸出: a

以上是一些 Python 中處理字串和字元的基本操作。Python 還提供了許多其他有用的函式和方法,可以更深入地處理字串和字元,更多好用函式可以參考官方文件。希望這個教學能幫助你入門字串和字元處理的基礎操作!

#Python







你可能感興趣的文章

Math.(floor/ceil/round) in JavaScript

Math.(floor/ceil/round) in JavaScript

JS30 Day 18 筆記

JS30 Day 18 筆記

MTR04_1120

MTR04_1120






留言討論